function varargout = mylock(This,What,varargin)
% mylock  [Not a public function] Lock or unlock links or sstate update equations.
%
% Backend IRIS function.
% No help provided.

% -IRIS Toolbox.
% -Copyright (c) 2007-2015 IRIS Solutions Team.

Action = varargin{end};
varargin(end) = [];

if isempty(varargin)
    List = @all;
else
    List = varargin;
end

pp = inputParser();
pp.addRequired('M',@ismodel);
pp.addRequired('What',@(x) ischar(x) ...
    && any(strncmpi(x,{'!l','!s'},2)));
pp.addRequired('List',@(x) isequal(x,@all) || iscellstr(x));
pp.parse(This,What,List);

%--------------------------------------------------------------------------

switch What(1:2)
    case '!l' % !links
        prop = 'Refresh';
    case '!s' % !sstate_updates
        prop = 'PosUpdate';
end

if Action == 0
    % Get lock status.
    name = [ This.name, mygetstd(This), mygetcorr(This) ];    
    if isequal(List,@all)
        pos = This.(prop)(This.(prop) < 0);
        varargout{1} = name( abs(pos) );
    else
        pos = doMatchNames();
        varargout{1} = This.(prop)(pos) < 0;
    end
else
    % Lock (Action=-1) or unlock (Action=1).
    if isequal(List,@all)
        pos = true(size(This.(prop)));
    else
        pos = doMatchNames();
    end
    if any(pos)
        This.(prop)(pos) = Action * abs(This.(prop)(pos));
    end
    varargout{1} = This;    
end


% Nested functions...


%**************************************************************************


    function PosLock = doMatchNames()
        ref = abs( This.(prop) );
        valid = true(size(List));
        usrPos = mylookupname(This,List);
        PosLock = [ ];
        for i = 1 : length(usrPos)
            match = usrPos(i)==ref;
            valid(i) = any(match);
            if valid(i)
                PosLock(end+1) = find(match); %#ok<AGROW>
            end
        end
        if any(~valid)
            utils.error('model:mylock', ...
                ['This is not a valid LHS name in ',What, ': %s.'], ...
                List{~valid});
        end
    end % doMatchNames()


end
